﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Expo.Training.BRule.Course;
using Expo.Training.DataAccess.Course;
using Expo.Training.Entity;
using Expo.Training.DataAccess.Resource;
using Expo.Training.BRule.Resource;
using Expo.Training.BRule.UserCenter.Favorite;
using Expo.Training.BRule.Exam;
using System.Data;
using Expo.Training.DataAccess.Activity;
using System.Text;

public partial class BM_Course_CourseInfoXB : Pagebase
{

    public int TotalRsNum
    {
        get
        {
            if (ViewState["TotalRsNum"] == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(ViewState["TotalRsNum"]);
            }
        }
        set
        {
            ViewState["TotalRsNum"] = value;
        }
    }
    public Guid cid = Guid.Empty;
    private bool needModifyPlan = false;
    public string CourseBeginDate = DateTime.Parse("1900-1-1").ToString("yyyy/MM/dd");
    public string URL = System.Configuration.ConfigurationManager.AppSettings["chaturl"];
    public int favtype = (int)FavoriteType.OnlineCourse;
    public int IsExpired = 0;
    public string favtitle = String.Empty;

    public Guid _activityId = Guid.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        cid = GetGuidValue("id");
        string ccid = GetStringValue("ccid");
        if (!string.IsNullOrEmpty(ccid))
            //this.a_goPortalCourseList.HRef = string.Format("/portal/xb/course/CourseListWithMenu.aspx?id={0}", ccid);

        if (cid.Equals(Guid.Empty))
        {
            AddBeginScript("noid","alert('当前课程错误！');");
            return;
        }
        if (!IsPostBack) 
        {
            
            //增加,页面加载时在Custmer_CourseAccess表中更新点击数的逻辑
            Customer_CourseAccess CCA = new Customer_CourseAccess();
            CCA.CourseID = cid;
            CCA.CustomerID = this.Customer.CustomerID;
            if (CCA.Exist())
            {
                CCA.StudyCount = CCA.StudyCount + 1;
                CCA.Update();
            }
            CCA.Dispose();


            BindCourseInfo();
            BindCourseResource();
            BindCourseResource1();

            BindActivityInfo();
        }
    }

    #region 绑定活动信息

    private void BindActivityInfo()
    {
        ActivityEntity _model = new ActivityEntity();
        List<ActivityEntity> _list = new List<ActivityEntity>();
        _list = ActivityModule.GetActivitysByCourseID(this.cid);
        if (_list.Count > 0)
        {
            _model = ActivityModule.GetActivitysByCourseID(this.cid)[0];

            this.spActivityTitle.InnerText = _model.ActivityTitle;
            this.dvActivityIntro.InnerHtml = _model.ActivityIntro;

            this._activityId = _model.ActivityID;
            ViewState["ActivityId"] = _model.ActivityID;
        }
        else
        {
            this.dvActivityIntro.InnerHtml = "当前课程没有相关活动";
            this.btnReg.Visible = false;
        }
        
    }
    
    #endregion

    #region 报名按钮单击事件

    protected void btnReg_Click(object sender, EventArgs e)
    {
        Response.Redirect("RegistrationXB.aspx?id=" + ViewState["ActivityId"]);
    }

    #endregion


    private void BindCourseResource()
    {

        DataTable objTable = BindResourceList();

        if (objTable != null && objTable.Rows.Count > 0)
        {
            ////this.dv_list.Visible = false;
            this.divShow.Visible = true;
            return;
        }
        else
        {
            //this.dv_list.Visible = true;
            this.divShow.Visible = false;
        }

        this.rpt_File.DataSource = objTable.DefaultView;
        this.rpt_File.DataBind();
    }
    #region [返回大小]
    public string GetSize(int size)
    {
        if (size == 0)
            return "0";
        if (size < 1024)
            return size.ToString() + " B";
        if (size / 1024 < 1024)
            return Convert.ToInt32(size / 1024).ToString() + " K";
        if (size / (1024 * 1024) < 1024)
            return String.Format("{0:N}", (float)(Convert.ToDouble(size) / Convert.ToDouble(1024 * 1024))) + " M";
        if (size / (1024 * 1024 * 1024) < 1024)
            return String.Format("{0:N}", (float)(Convert.ToDouble(size) / Convert.ToDouble(1024 * 1024 * 1024))) + " G";
        else
            return "0";
    }
    #endregion

    #region [获取用户名]
    public string GetUserName(Guid memberID)
    {
        Member_Info objMI = new Member_Info();
        objMI.MemberID = memberID;
        if (!objMI.Exist())
        {
            objMI.UserAccount = "未知";
        }
        return objMI.UserAccount;
    }
    #endregion

    private DataTable BindResourceList()
    {
        int totalCount = 0;
        DataTable dt = ResourceManager.GetResourceList(PagerDown.PageIndex + 1, PagerDown.PageSize,
                                                out totalCount, this.cid, this.Member.CustomerID,0);
        rpt_File.DataSource = dt;
        rpt_File.DataBind();
        PagerDown.TotalRecords = totalCount;

        ltlTotalThreadDown.Text = totalCount.ToString();

        this.TotalRsNum = PagerDown.CalculateTotalPages();
        if (TotalRsNum < 1)
        {
            TotalRsNum = 1;
        }

        ltlTotalPageDown.Text = this.TotalRsNum.ToString();

        if (this.TotalRsNum <= 1)
        {
            divGoPageDown.Visible = false;
        }

        if (dt.Rows.Count > 0)
        {
            this.divShow.Visible = true;
        }
        else
        {
            this.divShow.Visible = false;
        }
        return dt;
    }

    #region 页面跳转处理
    protected void lbtGoPageDown_Click(object sender, EventArgs e)
    {
        int curPage = 0;
        try
        {
            curPage = int.Parse(this.txtGoPageDown.Value.Trim());
        }
        catch
        {
            curPage = 0;
        }
        if (curPage == 0)
            curPage = 1;
        if (curPage > this.TotalRsNum)
            curPage = this.TotalRsNum;
        PagerDown.PageIndex = curPage - 1;
        BindCourseResource();
        this.txtGoPageDown.Value = string.Empty;
    }
    #endregion

    #region 分页处理
    protected void PagerDown_IndexChanged(object sender, EventArgs e)
    {
        BindCourseResource();
    }
    #endregion

    private void BindCourseInfo()
    {
        MemberCourseCell objMC = CourseManager.GetMemberCourseByID(this.Member.MemberID, cid, this.Member.CustomerID);

        if (objMC != null)
        {
            

            favtitle = objMC.CourseName;
            this.lblCourseName.Text = objMC.CourseName;
            //add 2015-04-03
            //资源列表中增加课程名称
            if (objMC.CourseName.Length > 16)
            {
                CourseNameForResourceList.Text = objMC.CourseName.Substring(0, 16);
            }
            else
            {
                CourseNameForResourceList.Text = objMC.CourseName;
            }
            this.a_Catalog.Text = objMC.CatalogName;
            //this.a_Catalog.NavigateUrl = string.Format("CourseListXB.aspx?id={0}", objMC.CatalogID);
            //this.a_goPortalCourseList.HRef = string.Format("/portal/xb/course/CourseListWithMenu.aspx?id={0}", objMC.CatalogID);
            this.lblLength.Text = (objMC.TotalPlayLength / 60).ToString()+"分钟";
            this.lblStudyTime.Text = objMC.StudyTime.ToString() + "学时";
            this.lblContent.Text = objMC.Description;
            this.lblTeacher.Text = "暂无";
            this.imgCoursePicture.Src = GetCourseImage(objMC.CoursePicture);
            GetCourseExam();

            Guid catalogID = Guid.Empty;

            Course_Info ci = new Course_Info();
            ci.CourseID = cid;
            if (ci.Exist())
            {
                this.ltCourseCode.Text = ci.SerialNumber;
                catalogID = ci.CourseSkill;
            }
            ci.Dispose();

            Course_CatalogV2 cc = new Course_CatalogV2();
            cc.CatalogID = catalogID;
            if (cc.Exist())
            {
                this.ltLevel.Text = cc.CatalogName;
            }
            cc.Dispose();

            //needPlan = CourseManager.ShowAddPlanButton(objMC.PlanCount, objMC.IsPublic, objMC.MemberExpiredDate, objMC.SelfPlanCount);

            //bool canStudy = CourseManager.ShowLearningButton(objMC.PlanCount, objMC.MemberExpiredDate);

            //if (needPlan == true || canStudy == true)
            //{
            //    btnStudy.Visible = true;
            //}
            //else
            //{
            //    if (objMC.IsPublic == 0)
            //    {
            //        btnStudy.Visible = false;
            //    }
            //    else
            //    {
                    //btnStudy.Visible = true;
                    needModifyPlan = true;
            //    }
            //}

            DateTime now = DateTime.Now;
            CourseBeginDate = objMC.BeginDate.ToString("yyyy/MM/dd");
            //课程授权日期过期或者课程结束日期过期(用户自定义)都视为过期，并且课程为非公开
            //yhuang 20110921 edit
            if (objMC.IsPublic == 0 && ((objMC.MemberExpiredDate < now && objMC.MemberExpiredDate.Year != 1900) || (objMC.ExpiredDate < now && objMC.ExpiredDate.Year != 1900)))
            {
                this.IsExpired = 1;
            }

           
        }
        else
        {
            Response.Redirect("CourseListXB.aspx");
        }
    }

    public void  GetCourseExam()
    {
        Customer_CourseAccess objCourse = new Customer_CourseAccess();
        objCourse.CourseID = cid;
        objCourse.CustomerID = this.Customer.CustomerID;
        if (objCourse.Exist())
        {
            if (objCourse.TestingID != Guid.Empty)
            {
                if (Examing.GetTestStatus(objCourse.TestingID) == ExamConst.TestStatus.End)
                {
                    this.lblExam.Text = "<a id=\"btnExam\" href=\"../Exam/ViewHistoryTestInfo.aspx?id=" + objCourse.TestingID.ToString() + "\" class=\"commonBtn_L\" style=\"vertical-align: middle;\"><span class=\"point\">开始考试</span></a>";
                }
                else
                {
                    if (TestingManager.DoAuthorize(objCourse.TestingID.ToString(), this.Member.MemberID.ToString(), this.Member.MemberID, 3, 0))
                    {
                        this.lblExam.Text = "<a id=\"btnExam\" href=\"../Exam/ViewProceedTestingInfo.aspx?id=" + objCourse.TestingID.ToString() + "\" class=\"commonBtn_L\" style=\"vertical-align: middle;\"><span class=\"point\">开始考试</span></a>";
                    }

                }
            }
        }
        objCourse.Dispose();
    }


    private DataTable BindResourceList1()
    {
        int totalCount = 0;
        DataTable dt = ResourceManager.GetResourceList(PagerDown.PageIndex + 1, PagerDown.PageSize,
                                                out totalCount, this.cid, this.Member.CustomerID, 1);
        rpt_File1.DataSource = dt;
        rpt_File1.DataBind();
        PagerDown1.TotalRecords = totalCount;

        ltlTotalThreadDown1.Text = totalCount.ToString();

        this.TotalRsNum = PagerDown1.CalculateTotalPages();
        if (TotalRsNum < 1)
        {
            TotalRsNum = 1;
        }

        ltlTotalPageDown1.Text = this.TotalRsNum.ToString();

        if (this.TotalRsNum <= 1)
        {
            divGoPageDown.Visible = false;
        }

        if (dt.Rows.Count > 0)
        {
            this.div1.Visible = true;
        }
        else
        {
            this.div1.Visible = false;
        }
        return dt;
    }

    #region 页面跳转处理
    protected void lbtGoPageDown1_Click(object sender, EventArgs e)
    {
        int curPage = 0;
        try
        {
            curPage = int.Parse(this.txtGoPageDown.Value.Trim());
        }
        catch
        {
            curPage = 0;
        }
        if (curPage == 0)
            curPage = 1;
        if (curPage > this.TotalRsNum)
            curPage = this.TotalRsNum;
        PagerDown.PageIndex = curPage - 1;
        BindCourseResource1();
        this.txtGoPageDown.Value = string.Empty;
    }
    #endregion

    #region 分页处理
    protected void PagerDown1_IndexChanged(object sender, EventArgs e)
    {
        BindCourseResource1();
    }
    #endregion

    private void BindCourseResource1()
    {

        DataTable objTable = BindResourceList1();

        if (objTable.DefaultView.Count <= 0)
        {
            ////this.dv_list.Visible = false;
            this.dv_NoResult.Visible = true;
            return;
        }
        else
        {
            //this.dv_list.Visible = true;
            this.dv_NoResult.Visible = false;
        }
        if (objTable == null)
        {
            return;
        }

        this.rpt_File1.DataSource = objTable.DefaultView;
        this.rpt_File1.DataBind();
    }

    protected void Item_Bound(object sender, RepeaterItemEventArgs e)
    {
        Literal ltProgress = (Literal)e.Item.FindControl("ltFinishPercent");
        double _classHour = 0;//总学时
        double _hisClassHour = 0;//已获学时
        
        decimal ltPass = 0;

        #region 获取完成度

        DataRowView _row = (DataRowView)e.Item.DataItem;
        Guid _resourceId = new Guid(_row["ResourceID"].ToString());

        Member_ResourceLog _log = new Member_ResourceLog();
        _log.MemberID = this.Member.MemberID;
        _log.ResourceID = _resourceId;

        if (_log.Exist()) 
        {
            _hisClassHour = _log.ClassHour;
        }

        Resource_Info _resource = new Resource_Info();
        _resource.ResourceID = _resourceId;
        if (_resource.Exist())
        {
            _classHour = _resource.ClassHour;
        }

        if (_classHour > 0)
        {
            ltPass = Convert.ToDecimal(_hisClassHour / _classHour) * 100;
        }

        #endregion

        StringBuilder sb = new StringBuilder();
        sb.Append("<span class=\"courseCompletedProgress\">");
        sb.Append("<script language=\"javascript\" type=\"text/javascript\">WriteProgress(" + ltPass.ToString() + ");</script>");
        sb.Append("</span>");
        ltProgress.Text = sb.ToString();
    }
}
